package a07_二叉树;

/**
 * <p>
 * a12_平衡二叉树复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/1/15
 */
public class a12_平衡二叉树复习2 {
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }

    public int getHeight(TreeNode node){
        if (node == null) {
            return 0;
        }
        int leftHeight = getHeight(node.left);
        if(leftHeight == -1){
            return -1;
        }
        int rightHeight = getHeight(node.right);
        if(rightHeight == -1){
            return -1;
        }
        if(Math.abs(leftHeight - rightHeight) > 1){
            return -1;
        }else {
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
}
